package com.example.event_resource_java.authority.controller.UserController;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.event_resource_java.authority.UserOpenfeign;
import com.example.event_resource_java.authority.server.UserServer;
import com.example.event_resource_java.commons.domain.UserDO;
import com.example.event_resource_java.commons.enums.EnumErrorCode;
import com.example.event_resource_java.commons.model.LoginBody;
import com.example.event_resource_java.commons.util.ApiResult;
import com.example.event_resource_java.commons.util.JWTUtil;
import com.example.event_resource_java.commons.util.PasswdUtils;
import com.example.event_resource_java.commons.util.StringUtil;
import com.example.event_resource_java.commons.vo.LoginVO.TokenVO;
import com.example.event_resource_java.commons.vo.PersonalInfoVO;
import com.example.event_resource_java.commons.vo.PersonalResetVO;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description:
 * @Author: ak
 * @CreateDate: 2024/4/24 8:49
 * @UpdateUser:
 * @UpdateDate: 2024/4/24 8:49
 * @UpdateRemark:
 * @Version: 1.0
 */
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServer userServer;
    @Autowired
    private UserOpenfeign userOpenfeign;


    @GetMapping("/getInfo")
    public ApiResult getUserInfo() {
        Long userId = JWTUtil.getUser().getId();
        UserDO userDO = userServer.getById(userId);
        PersonalInfoVO personalInfoVO = new PersonalInfoVO();
        BeanUtils.copyProperties(userDO, personalInfoVO);
        personalInfoVO.setOrgName(userDO.getOrgName());

        if (userDO.getType() == 1) {
            personalInfoVO.setName(userDO.getUsername());
        } else if (userDO.getType() == 0) {
            personalInfoVO.setName(userDO.getName());
        }

        StringBuffer sb = new StringBuffer();
        if (ObjectUtil.isNotEmpty(userDO.getProvince())) {
            sb.append(userDO.getProvince());
        }
        if (ObjectUtil.isNotEmpty(userDO.getCity())) {
            sb.append(userDO.getCity());
        }
        if (ObjectUtil.isNotEmpty(userDO.getDistrict())) {
            sb.append(userDO.getDistrict());
        }
        personalInfoVO.setOrgAddress(sb.toString());

        return ApiResult.success(personalInfoVO);
    }

    @CrossOrigin
    @PostMapping("/updateInfo")
    public ApiResult updateInfo(@RequestBody PersonalResetVO personalResetVO) {
        // base64 解密
        String newPassword = new String(Base64.getDecoder().decode(personalResetVO.getNewPassword()));
        String oldPassword = new String(Base64.getDecoder().decode(personalResetVO.getOldPassword()));

        Long userId = JWTUtil.getUser().getId();
        UserDO userDO = userServer.getById(userId);

        if (ObjectUtil.notEqual(userDO.getPassword(), PasswdUtils.get(oldPassword, userDO.getSalt()))) {
            return ApiResult.success("旧密码错误");
        }
        userDO.setPassword(PasswdUtils.get(newPassword, userDO.getSalt()));

        // 登录信息
        LoginBody loginBody = new LoginBody();
        loginBody.setPassword(newPassword);
        // 学生用户
        if (personalResetVO.getType() == 0) {
            loginBody.setUsername(userDO.getMobile());
        } else if (personalResetVO.getType() == 1) {
            // 老师用户
            loginBody.setUsername(userDO.getUsername());
        }

        try {
            // 更新密码
            userServer.updateById(userDO);

            ApiResult<?> login = userOpenfeign.login(loginBody);

            Map<String, String> newMap = StringUtil.mapStringToMap(login.getData().toString());
            TokenVO tokenVO = new TokenVO();
            tokenVO.setUName(newMap.get("uName"));
            tokenVO.setUserName(newMap.get("userName"));
            tokenVO.setType(Integer.parseInt(newMap.get("type")));
            tokenVO.setToken(newMap.get("token"));
            QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", tokenVO.getUserName());
            UserDO one = userServer.getOne(queryWrapper);
            tokenVO.setId(one.getId());

            // 返回token
            return ApiResult.success(EnumErrorCode.userLoginSuccess.getMsg(), tokenVO);
        } catch (AuthenticationException e) {
            return ApiResult.fail(EnumErrorCode.userLoginFail.getCode(), "登录失败");

        }
    }
}
